package com.zero.common.security.permit;

import com.zero.common.annotation.anonymous.Anonymous;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.RegExUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.*;
import java.util.regex.Pattern;

/**
 * 设置Anonymous注解允许匿名访问的url
 *
 * @author ruoyi
 */
@Configuration
public class PermitUrlList implements InitializingBean, ApplicationContextAware {

    // 用于保存Spring应用上下文的引用
    private ApplicationContext applicationContext;

    private final Pattern PATTERN = Pattern.compile("\\{(.*?)\\}");

    private final String ASTERISK = "*";

    @Getter
    @Setter
    private List<String> urls = new ArrayList<>();

    @Override
    public void afterPropertiesSet() {
        // 获取Spring上下文中的RequestMappingHandlerMapping，负责存储所有的请求映射信息
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        // 获取所有的请求映射信息，其中包含URL和对应的处理方法
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
        // 遍历所有的请求映射信息
        map.keySet().forEach(info -> {
            // 每一个方法
            HandlerMethod handlerMethod = map.get(info);

            /* 获取类上边的注解, 替代path variable 为 '*' */

            // 获取方法上的@Anonymous注解，如果有则进行处理
            Anonymous method = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), Anonymous.class);
            // 如果方法上有@Anonymous注解
            Optional.ofNullable(method).ifPresent(anonymous ->
                    // 替换URL中的路径变量为'*'
                    Objects.requireNonNull(info.getPatternsCondition().getPatterns())
                            .forEach(url -> urls.add(RegExUtils.replaceAll(url, PATTERN, ASTERISK)))
            );
            // 获取类上的@Anonymous注解，如果有则进行处理
            Anonymous controller = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), Anonymous.class);
            // 如果类上有@Anonymous注解
            Optional.ofNullable(controller).ifPresent(anonymous ->
                    // 替换URL中的路径变量为'*'
                    Objects.requireNonNull(info.getPatternsCondition().getPatterns())
                            .forEach(url -> urls.add(RegExUtils.replaceAll(url, PATTERN, ASTERISK))));
        });
    }

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        this.applicationContext = context;
    }
}
